//
//  SlideView.swift
//  ZYA
//
//  Created by 邱仙凯 on 2020/10/29.
//  Copyright © 2020 zwb. All rights reserved.
//

import UIKit
 
let contentLeftM:CGFloat = 60 // 侧滑留黑的宽度
class SlideView:UIView,DateWidgetable,UITableViewDelegate,UITableViewDataSource {
    
    
    var blackBg:UIView!
    var contentBg:UIView!
    var arr = [SlideContent]()
    var ori_arr = [SlideContent]()
    var tableView:UITableView!
    var resultClosure:((String)->())?
     var confirmClosure:(([SlideContent])->())? // 选中后的返回，直接取值使用
    var contentTopM = 80
    lazy var confirm:UIButton = {
        let v:UIButton = UIButton()
        v.backgroundColor = Theme.primaryColor()
        v.setTitle("确定", for: .normal)
        v.setTitleColor(.white, for: .normal)
        //        v.layer.masksToBounds = true
        //        v.layer.cornerRadius = 5
        return v
    }()
    lazy var reset:UIButton = {
        let v:UIButton = UIButton()
        v.backgroundColor = UIColor(kshex:"#f7f7f7")
        v.setTitle("重置", for: .normal)
        v.setTitleColor(.darkGray, for: .normal)
        //        v.layer.masksToBounds = true
        //        v.layer.cornerRadius = 5
        return v
    }()
    
    
    init(frame: CGRect,arr:[SlideContent]){
        self.arr = arr
        self.ori_arr = arr
        super.init(frame: frame)
        setup()
    }
    
    func setup() {
        let contentVWidth = KSGlobal.screenW - contentLeftM
        
        let gr = UITapGestureRecognizer(target: self, action: #selector(close))
        gr.numberOfTapsRequired = 1
        blackBg = UIView(frame: CGRect(x:KSGlobal.screenW,y: 0 ,width: KSGlobal.screenW,height: KSGlobal.screenH))
        blackBg.isUserInteractionEnabled = true
        blackBg.backgroundColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1).withAlphaComponent(0.7)
        addSubview(blackBg)
        blackBg.addGestureRecognizer(gr)
        
        
        contentBg = UIView(frame: CGRect(x:KSGlobal.screenW,y:0,width: contentVWidth,height: KSGlobal.screenH))
        contentBg.isUserInteractionEnabled = true
        contentBg.backgroundColor = .white
        addSubview(contentBg)
        
        tableView = UITableView(frame: CGRect(x:0,y:0,width: contentVWidth,height: KSGlobal.screenH - 50),style: .grouped)
        tableView.register(SlideCell.self, forCellReuseIdentifier: SlideCell.identifier)
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 44
        tableView.alpha = 1
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        
        contentBg.addSubview(tableView)
        
        
        let footer = UIView(frame: CGRect(x:0,y:KSGlobal.screenH - 50,width: contentVWidth,height: 35))
        
        reset.frame = CGRect(x:0,y:0,width: contentVWidth/2,height: 35)
        reset.addTouchUpInSideAction { _ in
            
             
                self.arr = self.ori_arr
                self.tableView.reloadData()
              
            
            
//            
//            for i in 0..<self.arr.count {
//                self.arr[i].startDate = ""
//                self.arr[i].endDate = ""
//                self.arr[i].inputStr = ""
//                if self.arr[i].dataArr.isSome {
//                    for j in 0..<self.arr[i].dataArr!.count {
//                        self.arr[i].dataArr![j].ks_selected = false
//                    }
//                }
//            }
//            self.tableView.reloadData()
            
        }
        
        footer.addSubview(reset)
        confirm.frame = CGRect(x:contentVWidth/2,y:0,width: contentVWidth/2,height: 35)
        confirm.addTouchUpInSideAction { _ in
            if let clo = self.confirmClosure {
                clo(self.arr)
            }
        }
        footer.addSubview(confirm)
        
        contentBg.addSubview(footer)
        
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.arr.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.arr[section].open.isSome {
            return self.arr[section].open! ? 1 : 0
        } else {
            return 1
        }
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let contentVWidth = KSGlobal.screenW - contentLeftM
        let bg = UIView(frame: CGRect(x:0,y:0,width: contentVWidth,height: 30))
    
        
        let tap = UITapGestureRecognizer()
        tap.numberOfTapsRequired = 1
        tap.addTap { _ in
            
            if self.arr[section].open.isSome {
                self.arr[section].open = !self.arr[section].open!
                let set = IndexSet(integer:section)
                tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
            }
            
            
            
            
        }
        
        bg.addGestureRecognizer(tap)
        
        
        let lab = UILabel(frame: CGRect(x:10,y:0,width: contentVWidth - 10,height: 30))
        lab.font = UIFont.systemFont(ofSize: 16)
        lab.text = self.arr[section].title
        bg.addSubview(lab)
        if self.arr[section].open.isSome {
            let img = UIImageView(image: UIImage(named: self.arr[section].open! ? "filter_up" : "filter_down"))
            img.frame = CGRect(x:contentVWidth - 20,y:12,width: 12,height: 8)
            bg.addSubview(img)
        } else {
            
        }
        
        
        return bg
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 量少，不复用，防止串数据
//        guard let cell = tableView.dequeueReusableCell(withIdentifier: SlideCell.identifier, for: indexPath) as? SlideCell else {
//            fatalError()
//        }
        let cell = SlideCell(style:UITableViewCell.CellStyle.default, reuseIdentifier: SlideCell.identifier)
        
        cell.model = self.arr[indexPath.section]
        cell.multiItemClosure = { [indexPath] tag in
            self.arr[indexPath.section].dataArr![tag].ks_selected = !self.arr[indexPath.section].dataArr![tag].ks_selected
   
        }
        cell.singleItemClosure = { [indexPath] oldtag,newtag in
            if let old = oldtag {
                self.arr[indexPath.section].dataArr![old].ks_selected = false
            }
            self.arr[indexPath.section].dataArr![newtag].ks_selected = true
   
        }
        cell.minMoneyClosure = { [indexPath] str in
            self.arr[indexPath.section].minMoney = str
         }
        cell.maxMoneyClosure = { [indexPath] str in
            self.arr[indexPath.section].maxMoney = str
         }
        cell.dateClosure = { tag in
            if tag == 1 {
                
                let max:String? = self.arr[indexPath.section].endDate.isEmpty ? nil : self.arr[indexPath.section].endDate
                self.showDateSelect( UIApplication.shared.keyWindow!.rootViewController!,maxDate: max) { (str) in
                   
                        self.arr[indexPath.section].startDate = str
                  
                    
                    let set = IndexSet(integer:indexPath.section)
                    tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
                }
            } else {
                let min:String? = self.arr[indexPath.section].startDate.isEmpty ? nil : self.arr[indexPath.section].startDate

                self.showDateSelect( UIApplication.shared.keyWindow!.rootViewController!,minDate:min) { (str) in
                  
                        self.arr[indexPath.section].endDate = str
                
                    
                    let set = IndexSet(integer:indexPath.section)
                    tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
                }
            }
            
             
        }
        cell.btnFieldClosure = {
            if let clo = self.arr[indexPath.section].actionClo {
                clo(indexPath.section)
            }
        }
        cell.textFClosure = { str in
            self.arr[indexPath.section].inputStr = str
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        self.close()
        
    }
    
    
    
    override func willMove(toSuperview newSuperview: UIView?) {
        
        if newSuperview.isSome {
            self.blackBg.ks_x = 0
            UIView.animate(withDuration: 0.2) { //  出现时
                 self.contentBg.ks_x = contentLeftM
            }
        }
        
    }
    
    @objc func close(){
        self.blackBg.ks_x = KSGlobal.screenW
        UIView.animate(withDuration: 0.2) {
             self.contentBg.ks_x = KSGlobal.screenW
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
            self.removeFromSuperview()
        }
        
        
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

class SlideCell: UITableViewCell {
    
   private var itemLeftM:CGFloat = 10
     var multiItemClosure:((Int)->())? // 多选的 选中按钮 tag 返回
    var singleItemClosure:((Int?,Int)->())?  // 单选的选中按钮返回 0- 旧的选中tag，1- 新的选中tag
    var dateClosure:((Int)->())? // 1  开始  2 结束
    var textFClosure:((String)->())?
    var btnFieldClosure:(()->())?

    var minMoneyClosure:((String)->())? // 小金额返回
    var maxMoneyClosure:((String)->())? // 大金额返回
    private lazy var startBtn:SlideButton = {
        let lbtn = SlideButton()
        lbtn.layer.masksToBounds = true
        lbtn.layer.cornerRadius = 5
        lbtn.layer.borderWidth = 1
        lbtn.setTitle("请选择", for: .normal)
        lbtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        lbtn.layer.borderColor = UIColor.lightGray.cgColor
        return lbtn
    }()
    private lazy var line:UIView = {
        let line = UIView()
        line.backgroundColor = .lightGray
        return line
    }()
    private lazy var endBtn:SlideButton = {
        let rbtn = SlideButton()
        rbtn.layer.masksToBounds = true
        rbtn.layer.cornerRadius = 5
        rbtn.layer.borderWidth = 1
        rbtn.setTitle("请选择", for: .normal)
        rbtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        rbtn.layer.borderColor = UIColor.lightGray.cgColor
        return rbtn
    }()
    private lazy var textMin:UITextField = {
        let lbtn: UITextField = UITextField()
        lbtn.layer.masksToBounds = true
        lbtn.textAlignment = .center
        lbtn.layer.cornerRadius = 5
        lbtn.layer.borderWidth = 1
        lbtn.font = UIFont.systemFont(ofSize: 15)
        lbtn.layer.borderColor = UIColor.lightGray.cgColor
        lbtn.keyboardType = .numbersAndPunctuation
        lbtn.placeholder = "请输入"
        return lbtn
    }()
    private lazy var textMax:UITextField = {
        let lbtn: UITextField = UITextField()
        lbtn.layer.masksToBounds = true
        lbtn.textAlignment = .center
        lbtn.layer.cornerRadius = 5
        lbtn.layer.borderWidth = 1
        lbtn.font = UIFont.systemFont(ofSize: 15)
        lbtn.layer.borderColor = UIColor.lightGray.cgColor
        lbtn.keyboardType = .numbersAndPunctuation

        lbtn.placeholder = "请输入"
        return lbtn
    }()
    private lazy var btnField:UIButton = {
        let lbtn: UIButton = UIButton()
        lbtn.layer.masksToBounds = true
        lbtn.setTitleColor(.black, for: .normal)
        lbtn.titleLabel?.textAlignment = .center
        lbtn.layer.cornerRadius = 5
        lbtn.layer.borderWidth = 1
        lbtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        lbtn.layer.borderColor = UIColor.lightGray.cgColor
        return lbtn
    }()
    private lazy var textF:UITextField = {
        let lbtn: UITextField = UITextField()
        lbtn.layer.masksToBounds = true
        lbtn.textAlignment = .center
        lbtn.layer.cornerRadius = 5
        lbtn.layer.borderWidth = 1
        lbtn.font = UIFont.systemFont(ofSize: 15)
        lbtn.layer.borderColor = UIColor.lightGray.cgColor
        lbtn.placeholder = "请输入"
        return lbtn
    }()
    var itemBtnArr = [SlideItemButton]()
    private var singleSelectedBtn:SlideItemButton?
    var model:SlideContent? {
        didSet {
            if let model = model {
                startBtn.isHidden = true
                line.isHidden = true
                endBtn.isHidden = true
                textF.isHidden = true
                btnField.isHidden = true
                
                if model.type == .dateRegion {
                    startBtn.isHidden = false
                    startBtn.setTitle(model.startDate, for: .normal)
                    startBtn.addTouchUpInSideAction { _ in
                        if let clo = self.dateClosure {
                            clo(1)
                        }
                        
                    }
                    if startBtn.superview.isNone {
                        self.contentView.addSubview(startBtn)
                        startBtn.snp.makeConstraints { (make) in
                            make.left.equalTo(self.contentView).offset(itemLeftM)
                            make.right.equalTo(self.contentView.snp.centerX).offset(-10)
                            make.top.equalTo(self.contentView).offset(6)
                            make.height.equalTo(35)
                            make.bottom.equalTo(self.contentView).offset(-6)
                        }
                    }
                    line.isHidden = false
                    if line.superview.isNone {
                        self.contentView.addSubview(line)
                        line.snp.makeConstraints { (make) in
                            make.centerY.equalTo(startBtn)
                            make.width.equalTo(5)
                            make.centerX.equalTo(self.contentView)
                            make.height.equalTo(1)
                        }
                    }
                    endBtn.isHidden = false
                    endBtn.setTitle(model.endDate, for: .normal)
                    endBtn.addTouchUpInSideAction { _ in
                        if let clo = self.dateClosure {
                            clo(2)
                        }
                    }
                    if endBtn.superview.isNone {
                        self.contentView.addSubview(endBtn)
                        endBtn.snp.makeConstraints { (make) in
                            make.right.equalTo(self.contentView).offset(-itemLeftM)
                            make.left.equalTo(self.contentView.snp.centerX).offset(10)
                            make.centerY.equalTo(startBtn)
                            make.height.equalTo(35)
                        }
                    }
                    
                    
                } else if  model.type == .moneyRegion {
                    textMin.isHidden = false
                    textMin.text = model.minMoney
                    textMin.addTextChangeClosure { text in
                             if let clo = self.minMoneyClosure {
                                 clo(text.text.unwrap)
                            }
                        }
                    if textMin.superview.isNone {
                        self.contentView.addSubview(textMin)
                        textMin.snp.makeConstraints { (make) in
                            make.left.equalTo(self.contentView).offset(itemLeftM)
                            make.right.equalTo(self.contentView.snp.centerX).offset(-10)
                            make.top.equalTo(self.contentView).offset(6)
                            make.height.equalTo(35)
                            make.bottom.equalTo(self.contentView).offset(-6)
                        }
                    }
                    line.isHidden = false
                    if line.superview.isNone {
                        self.contentView.addSubview(line)
                        line.snp.makeConstraints { (make) in
                            make.centerY.equalTo(textMin)
                            make.width.equalTo(5)
                            make.centerX.equalTo(self.contentView)
                            make.height.equalTo(1)
                        }
                    }
                    textMax.isHidden = false
                    textMax.text = model.maxMoney
                    textMax.addTextChangeClosure { text in
                            if let clo = self.maxMoneyClosure {
                                clo(text.text.unwrap)
                            }
                        }
 
                    if textMax.superview.isNone {
                        self.contentView.addSubview(textMax)
                        textMax.snp.makeConstraints { (make) in
                            make.right.equalTo(self.contentView).offset(-itemLeftM)
                            make.left.equalTo(self.contentView.snp.centerX).offset(10)
                            make.centerY.equalTo(textMin)
                            make.height.equalTo(35)
                        }
                    }
                    
                } else if model.type == .multiSelect || model.type == .singleSelect {
                    
                    if itemBtnArr.count > 0 {
                        for i in 0..<itemBtnArr.count {
                          
                            itemBtnArr[i].setSelected(model.dataArr![i].ks_selected)
                        }
                    } else {
                        let padH = 10
                        let padV = 6
                        let itemH = 30
                        let rowx = model.numberOfRow
                        let contentVWidth = KSGlobal.screenW - contentLeftM
                        let itemW = (Int(contentVWidth) - padH * (rowx + 1)) / rowx
                        for i in 0..<model.dataArr!.count {
                            let btn = SlideItemButton()
                            btn.tag = i
                            itemBtnArr.append(btn)
                            btn.setTitle(model.dataArr![i].title, for: .normal)
                            let sesS = model.dataArr![i].ks_selected
                            btn.setSelected(sesS)
                            if sesS {
                                self.singleSelectedBtn = btn
                            }
                            self.contentView.addSubview(btn)
                            btn.addTouchUpInSideAction { [i] _ in
                                
                                if model.type == .singleSelect {
                                    if self.singleSelectedBtn.isSome {
                                        self.singleSelectedBtn?.setSelected(false)
                                        btn.setSelected(true)
                                    } else {
                                        btn.setSelected(true)
                                    }
                                    
                                    if let clo = self.singleItemClosure {
                                        clo(self.singleSelectedBtn?.tag,btn.tag)
                                    }
                                    self.singleSelectedBtn = btn
                                } else  {
                                    btn.setSelected(!model.dataArr![i].ks_selected)
                                    if let clo = self.multiItemClosure {
                                        clo(i)
                                    }
                                }
                                
                                
                                
                            }
                            btn.snp.makeConstraints { (make) in
                                make.width.equalTo(itemW)
                                make.height.equalTo(itemH)
                                make.left.equalTo(self.contentView).offset(padH + i%rowx * (itemW + padH))
                                make.top.equalTo(i/rowx * (itemH + padV))
                                if i == (model.dataArr!.count - 1) {
                                    make.bottom.equalTo(self.contentView).offset(-10)
                                }
                            }
                        }
                    }
                    
                    
                    
                    
                    
                } else if model.type == .singleInput {
                    textF.isHidden = false
                    textF.text = model.inputStr
                    
                    textF.addTextChangeClosure { text in
                             if let clo = self.textFClosure {
                                 clo(text.text.unwrap)
                            }
                        }
                        if textF.superview.isNone {
                        self.contentView.addSubview(textF)
                        textF.snp.makeConstraints { (make) in
                            make.left.equalTo(self.contentView).offset(itemLeftM)
                            make.right.equalTo(self.contentView).offset(-itemLeftM)
                            make.top.equalTo(self.contentView).offset(6)
                            make.bottom.equalTo(self.contentView).offset(-6)
                            make.height.equalTo(35)
                        }
                    }
                    
                    
                } else if model.type == .actionClo {
                    btnField.isHidden = false
                     btnField.setTitle(model.inputStr, for: .normal)
                    btnField.addTouchUpInSideAction({ _ in
                        if let clo = self.btnFieldClosure {
                            clo()
                        }
                    })
                  
                        if btnField.superview.isNone {
                        self.contentView.addSubview(btnField)
                            btnField.snp.makeConstraints { (make) in
                            make.left.equalTo(self.contentView).offset(itemLeftM)
                            make.right.equalTo(self.contentView).offset(-itemLeftM)
                            make.top.equalTo(self.contentView).offset(6)
                            make.bottom.equalTo(self.contentView).offset(-6)
                            make.height.equalTo(35)
                        }
                    }
                    
                    
                }
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        
    }
    
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
}




